from flask import request, jsonify
from flask_restx import Resource, Namespace
from ..models.user import User
from ..services.auth import AuthService
from .. import api, db

# 创建用户管理命名空间
ns = api.namespace('users', description='用户管理相关接口')

@ns.route('')
class UserList(Resource):
    def get(self):
        """获取所有用户列表"""
        # 验证请求中的token
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return {'message': '未提供认证令牌'}, 401
        
        try:
            token = auth_header.split(' ')[1]
            current_user = AuthService.verify_token(token)
            if not current_user:
                return {'message': '无效的认证令牌'}, 401
            
            # 获取所有用户
            users = User.query.all()
            return [user.to_dict() for user in users]
        except Exception as e:
            return {'message': str(e)}, 500

@ns.route('/<int:user_id>')
class UserResource(Resource):
    def get(self, user_id):
        """获取指定用户信息"""
        # 验证请求中的token
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return {'message': '未提供认证令牌'}, 401
        
        try:
            token = auth_header.split(' ')[1]
            current_user = AuthService.verify_token(token)
            if not current_user:
                return {'message': '无效的认证令牌'}, 401
            
            # 获取指定用户
            user = User.query.get(user_id)
            if not user:
                return {'message': '用户不存在'}, 404
            
            # 删除用户
            db.session.delete(user)
            db.session.commit()
            return {'message': '用户已删除'}, 200
        except Exception as e:
            db.session.rollback()
            return {'message': str(e)}, 500query.get(user_id)
            if not user:
                return {'message': '用户不存在'}, 404
            
            return user.to_dict()
        except Exception as e:
            return {'message': str(e)}, 500
    
    def put(self, user_id):
        """更新用户信息"""
        # 验证请求中的token
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return {'message': '未提供认证令牌'}, 401
        
        try:
            token = auth_header.split(' ')[1]
            current_user = AuthService.verify_token(token)
            if not current_user:
                return {'message': '无效的认证令牌'}, 401
            
            # 获取指定用户
            user = User.query.get(user_id)
            if not user:
                return {'message': '用户不存在'}, 404
            
            # 删除用户
            db.session.delete(user)
            db.session.commit()
            return {'message': '用户已删除'}, 200
        except Exception as e:
            db.session.rollback()
            return {'message': str(e)}, 500query.get(user_id)
            if not user:
                return {'message': '用户不存在'}, 404
            
            # 更新用户信息
            data = request.get_json()
            if 'username' in data:
                user.username = data['username']
            if 'email' in data:
                user.email = data['email']
            if 'is_active' in data:
                user.is_active = data['is_active']
            
            db.session.commit()
            return {'message': '用户信息已更新', 'user': user.to_dict()}
        except Exception as e:
            db.session.rollback()
            return {'message': str(e)}, 500
    
    def delete(self, user_id):
        """删除用户"""
        # 验证请求中的token
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return {'message': '未提供认证令牌'}, 401
        
        try:
            token = auth_header.split(' ')[1]
            current_user = AuthService.verify_token(token)
            if not current_user:
                return {'message': '无效的认证令牌'}, 401
            
            # 不能删除自己
            if current_user.id == user_id:
                return {'message': '不能删除当前登录用户'}, 400
            
            # 获取指定用户
            user = User.query.get(user_id)
            if not user:
                return {'message': '用户不存在'}, 404
            
            # 删除用户
            db.session.delete(user)
            db.session.commit()
            return {'message': '用户已删除'}, 200
        except Exception as e:
            db.session.rollback()
            return {'message': str(e)}, 500